package com.hougong.im.pool;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 连接池，用户维护已与服务器建立连接的Client
 * <p>
 * @author lsz.
 */
public class ConnPool {
    private static final Logger logger = LoggerFactory.getLogger(ConnPool.class);

    private ConnPool() {
    }

    // 用于存放在线用户的id和channel
    private static ConcurrentHashMap<Long, Channel> tcpMap = new ConcurrentHashMap<>();
    //DUP  uID  -----> UDP地址
    private static volatile ConcurrentHashMap<Long,InetSocketAddress> udpMap=new ConcurrentHashMap<>();


    /**
     * 添加连接
     * @param uid
     * @param channel
     * @return
     */
    public static boolean addTcp(Long uid, Channel channel) {
        Channel result = tcpMap.put(uid, channel);

        logger.info("Conn池 添加成功(uid=" + uid + " channel=" + channel + ")");
        return true;
    }

  /*  private static Long getUdpMapKey(Long uid){
        if(toUid==null){
            return fromUid+"";
        }else {
            return fromUid+"#"+toUid;
        }
        return uid;
    }*/
    public static boolean addUDP(Long fromUid,InetSocketAddress channel) {
        InetSocketAddress result = udpMap.put(fromUid, channel);
        logger.info("UDP池 添加成功(uid=" + fromUid + " channel=" + channel + ")");
        return true;
    }




    /**
     * 删除udp连接
     *
     * @return
     */
    public  static boolean removeUDP(Long fromUid ) {
        InetSocketAddress result = udpMap.remove(fromUid);
        return true;
    }

    /**
     * 删除udp连接
     * @param uid
     * @return
     */
    public  static boolean removeTCP(Long uid) {
        Channel result = tcpMap.remove(uid);
        if (result != null) {
            logger.info("Conn池 移除成功(username=" + uid + ")");
            return true;
        } else {
            logger.warn("Conn池 移除失败(username=" + uid + ")");
            return false;
        }
    }

    /**
     * 查找连接
     *
     * @param uid
     * @return
     */
    public  static Channel queryTCP(Long uid) {
        return tcpMap.get(uid);
    }

    /**
     * 查找udp连接
     *
     * @param uid
     * @return
     */
    public  static InetSocketAddress queryUDP(Long uid) {
        return udpMap.get(uid);
    }


    /**
     * 查找用户
     *
     * @param channel
     * @return
     */
    public  static Long queryTCP(Channel channel) {
        Set<Map.Entry<Long, Channel>> entries = tcpMap.entrySet();
        Iterator<Map.Entry<Long, Channel>> ite = entries.iterator();
        while (ite.hasNext()) {
            Map.Entry<Long, Channel> entry = ite.next();
            if (channel.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }


}